// 媒体文件相关API服务
import pool from '../config/database';

class MediaService {
  // 上传媒体文件记录
  async createMediaFile(mediaData) {
    const { 
      user_id, 
      article_id, 
      file_name, 
      original_name, 
      file_type, 
      file_size, 
      file_url, 
      mime_type,
      width,
      height,
      duration
    } = mediaData;
    
    const query = `
      INSERT INTO media_files (
        user_id, article_id, file_name, original_name, file_type, 
        file_size, file_url, mime_type, width, height, duration
      )
      VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
      RETURNING *
    `;
    
    const values = [
      user_id, article_id, file_name, original_name, file_type,
      file_size, file_url, mime_type, width, height, duration
    ];
    
    try {
      const result = await pool.query(query, values);
      return result.rows[0];
    } catch (error) {
      console.error('创建媒体文件记录失败:', error);
      throw error;
    }
  }

  // 获取作品的媒体文件
  async getMediaFilesByArticle(articleId) {
    const query = `
      SELECT * FROM media_files 
      WHERE article_id = $1 
      ORDER BY created_at DESC
    `;
    
    try {
      const result = await pool.query(query, [articleId]);
      return result.rows;
    } catch (error) {
      console.error('获取媒体文件失败:', error);
      throw error;
    }
  }

  // 获取用户的媒体文件
  async getMediaFilesByUser(userId, options = {}) {
    const { page = 1, limit = 20, file_type } = options;
    const offset = (page - 1) * limit;
    
    let query = `
      SELECT * FROM media_files 
      WHERE user_id = $1
    `;
    
    const values = [userId];
    let paramIndex = 2;
    
    if (file_type) {
      query += ` AND file_type = $${paramIndex}`;
      values.push(file_type);
      paramIndex++;
    }
    
    query += ` ORDER BY created_at DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`;
    values.push(limit, offset);
    
    try {
      const result = await pool.query(query, values);
      
      // 获取总数
      let countQuery = `SELECT COUNT(*) as total FROM media_files WHERE user_id = $1`;
      const countValues = [userId];
      
      if (file_type) {
        countQuery += ` AND file_type = $2`;
        countValues.push(file_type);
      }
      
      const countResult = await pool.query(countQuery, countValues);
      const total = parseInt(countResult.rows[0].total);
      
      return {
        files: result.rows,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取用户媒体文件失败:', error);
      throw error;
    }
  }

  // 删除媒体文件
  async deleteMediaFile(fileId, userId) {
    const query = `
      DELETE FROM media_files 
      WHERE id = $1 AND user_id = $2
      RETURNING *
    `;
    
    try {
      const result = await pool.query(query, [fileId, userId]);
      if (result.rows.length === 0) {
        throw new Error('文件不存在或无权限删除');
      }
      return result.rows[0];
    } catch (error) {
      console.error('删除媒体文件失败:', error);
      throw error;
    }
  }

  // 创建视频记录
  async createVideo(videoData) {
    const { 
      user_id, 
      article_id, 
      video_url, 
      video_type, 
      title, 
      description, 
      thumbnail_url, 
      duration 
    } = videoData;
    
    const query = `
      INSERT INTO videos (
        user_id, article_id, video_url, video_type, 
        title, description, thumbnail_url, duration
      )
      VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
      RETURNING *
    `;
    
    const values = [
      user_id, article_id, video_url, video_type,
      title, description, thumbnail_url, duration
    ];
    
    try {
      const result = await pool.query(query, values);
      return result.rows[0];
    } catch (error) {
      console.error('创建视频记录失败:', error);
      throw error;
    }
  }

  // 获取作品的视频
  async getVideosByArticle(articleId) {
    const query = `
      SELECT * FROM videos 
      WHERE article_id = $1 
      ORDER BY created_at DESC
    `;
    
    try {
      const result = await pool.query(query, [articleId]);
      return result.rows;
    } catch (error) {
      console.error('获取视频失败:', error);
      throw error;
    }
  }


}

export default new MediaService();